<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
  #box2{
    background: red;
    width: 50px;
    height: 50px;
  }
  </style>

  <div id="box">{{boxhtml}}</div>
  <input id="input" type="text" oninput="textchange()">

  <br />
  <div id="box2" v-if='box2show'></div>
  <button onclick="show()">显示</button>
  <button onclick="hide()">隐藏</button>
</head>
<body>
  <script type="text/javascript">

  /*-----------------原理-----------------*/
  var Book = {}
  var name = '';
  Object.defineProperty(Book, 'name', {
    set: function (value) {
      name = value;
      console.log('你取了一个书名叫做' + value);
    },
    get: function () {
      return '《' + name + '》'
    }
  })
  
  Book.name = 'vue权威指南';  // 你取了一个书名叫做vue权威指南
  console.log(Book.name);  // 《vue权威指南》

  /*-----------------以下为实现-----------------*/

  var reg = /\{\{(.*)\}\}/;

  var box = document.getElementById('box');
  var boxhtml;
  
  //defineProperty实现set,get
  Object.defineProperty(
    box,//box本身就是一个对象，也可以var boxObj = {} 代替
    reg.exec(box.innerHTML)[1],//正则匹配box里的内容,去除{{}},只获取双花括号里的内容
    {
      set:function(value){
        boxhtml = value;
        box.innerHTML = value;
        console.log('设置属性')
      },
      get:function(){
        console.log('获取属性')
        return boxhtml;
      }
    }
  )

  function textchange(){
    var input = document.getElementById('input');
    box.boxhtml = input.value
  }

  //初始化
  box.boxhtml = '';



  
  var box2 = document.getElementById('box2');
  var box2show;
  Object.defineProperty(
    box2,
    box2.getAttribute('v-if'),
    {
      set:function(value){
        box2show = value;
        box2.style.display = value?'':'none';
      },
      get:function(){
        return box2show;
      }
    }
  )

  function show(){
    box2.box2show = true;
  }
  function hide(){
    box2.box2show = false;
  }
  </script>
</body>
</html>